//
//  BookViewModel.swift
//  SwiftUIBook
//
//  Created by True on 2023/8/3.
//

import Foundation

class BookAPPVM: ObservableObject {
    @Published private var model: BookAPPData = BookAPPData()
    
    var readText: String {
        return model.readText
    }
    
    var sites: [BookAPPData.FavoriteSite] {
        return model.sites
    }
    
    var books: [BookAPPData.Book] {
        return model.books
    }
    
    var curUrlStr = ""
    
    var nextAction: (()->Void)?
    
    func dealNewHtml(_ str: String, isReading: Bool) {
        if !isReading {
            model.chapterClean()
        }
        let (title, text) = dealHtmlString(str)
        let chapter = BookAPPData.Chapter(title: title, text: text)
        model.newChapterInfo(chapter)
    }
    
    func addBook(_ book: BookAPPData.Book) {
        model.addBook(book)
    }
    
    func deleteBook(_ book: BookAPPData.Book) {
        model.deleteBook(book)
    }
    
    func deleteBook(_ indexSet: IndexSet) {
        model.deleteBook(at: indexSet)
    }
    
    func addSite(_ site: BookAPPData.FavoriteSite) {
        model.addSite(site)
    }
    
    func requestNext() {
        nextAction?()
    }
    
    
    private func dealHtmlString(_ html: String) -> (String, String) {
        
        // 逐一测试规则
        let regular1 = re.compile("<div\\sclass=\"yd_text2\".*?>(.*?)</div>", flags: .dotMatchesLineSeparators)
        if let matches = regular1.search(html) {
            var text = matches.group(1)!
            text = (text as NSString).replacingOccurrences(of: "<br>", with: "\n")
            text = (text as NSString).replacingOccurrences(of: "&nbsp;", with: " ")
            let re_p = re.compile("<p.*?>(.*?)</p>", flags: .dotMatchesLineSeparators)
            let list = re_p.finditer(text)
            let s = list.map { p -> String in
                if let p_str = p.group(1) {
                    return p_str + "\n"
                }
                return ""
            }.joined()
            text = (s as NSString).trimmingCharacters(in: .whitespacesAndNewlines)
            
            let title_re = re.compile("<div\\sclass=\"novel\".*?>.*?<h1>(.*?)</h1>", flags: .dotMatchesLineSeparators)
            var title = ""
            if let title_matches = title_re.search(html) {
                title = title_matches.group(1)!
            }
            
            return (title, text)
        }
        
        // 友友小说
        // 必须在 飞速中文 前面，不然会被 飞速中文 规则匹配，造成错误
        let regular3 = re.compile("<div\\sid=\"booktxt\".*?>(.*?)</div>", flags: .dotMatchesLineSeparators)
        if let matches = regular3.search(html) {
            
            let html1 = html.replacingOccurrences(of: "<div><script>try {t();} catch (err) {}</script></div>", with: "")
            let html2 = html1.replacingOccurrences(of: "<div><script>try {b();} catch (err) {}</script></div>", with: "")
            guard let matches2 = regular3.search(html2) else {
                return ("", "")
            }
            var text = matches2.group(1)!
            text = (text as NSString).replacingOccurrences(of: "<br>", with: "\n")
            text = (text as NSString).replacingOccurrences(of: "&nbsp;", with: " ")
            let re_p = re.compile("<p.*?>(.*?)</p>", flags: .dotMatchesLineSeparators)
            let list = re_p.finditer(text)
            let s = list.map { p -> String in
                if var p_str = p.group(1) {
                    p_str = p_str.trimmingCharacters(in: .whitespacesAndNewlines)
                    return p_str + "\n"
                }
                return ""
            }.joined()
            text = (s as NSString).trimmingCharacters(in: .whitespacesAndNewlines)
            
            let title_re = re.compile("<h1\\sclass=\"bookname\".*?>(.*?)（.*?）</h1>", flags: .dotMatchesLineSeparators)
            var title = ""
            if let title_matches = title_re.search(html) {
                title = title_matches.group(1)!
            }
            
            return (title, text)
        }
        
        // 飞速中文
        let regular2 = re.compile("<div\\sid=\"content\".*?>(.*?)</div>", flags: .dotMatchesLineSeparators)
        if let matches = regular2.search(html) {
            var text = matches.group(1)!
            text = (text as NSString).replacingOccurrences(of: "<br>", with: "\n")
            text = (text as NSString).replacingOccurrences(of: "&nbsp;", with: " ")
            let re_p = re.compile("<p.*?>(.*?)</p>", flags: .dotMatchesLineSeparators)
            let list = re_p.finditer(text)
            let s = list.map { p -> String in
                if let p_str = p.group(1) {
                    return p_str + "\n"
                }
                return ""
            }.joined()
            text = (s as NSString).trimmingCharacters(in: .whitespacesAndNewlines)
            
            let title_re = re.compile("<p\\sclass=\"chaptertitle\".*?>(.*?)</p>", flags: .dotMatchesLineSeparators)
            var title = ""
            if let title_matches = title_re.search(html) {
                title = title_matches.group(1)!
            }
            
            return (title, text)
        }
        
        
        
        return ("", "")
        
    }
}
